package com.bryant.demo05.ui.login

import android.Manifest
import android.content.Intent
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.Toast
import android.provider.Settings
import androidx.lifecycle.lifecycleScope
import com.bryant.demo05.MainActivity

import com.bryant.demo05.base.BaseBindingActivity
import com.bryant.demo05.bean.LoginRequest
import com.bryant.demo05.databinding.AcLoginBinding
import com.bryant.demo05.storage.TokenPreferences
import com.bryant.demo05.utils.AmapUtils
import com.bryant.demo05.utils.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import pub.devrel.easypermissions.EasyPermissions

class LoginActivity : BaseBindingActivity<AcLoginBinding>() {
    private val mPermissions = if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) { // Android 12及以下（API 32）
        arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE, // 低版本需要此权限
            Manifest.permission.CAMERA
        )
    } else { // Android 13及以上（API 33+）
        arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.CAMERA
        )
    }
    private val RC_LOCATION_PERM = 123

    private var hasInitAMap = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 检查权限
        checkRequiredPermissions()
        // 1. 监听布局登录按钮
        binding.tvLogin.setOnClickListener {
            // 点击执行该事件
            tologin()
        }

    }

    override fun initBinding(layoutInflater: LayoutInflater): AcLoginBinding {
        return AcLoginBinding.inflate(layoutInflater)
    }

    private fun tologin() {
        // 1. 获取用户输入的账号和密码
        val username = binding.etUsername.text.toString()
        val password = binding.etPassword.text.toString()

        // 2. 判断账号和密码是否为空
        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入账号和密码", Toast.LENGTH_SHORT).show()
            return
        }

        // 3. 发送登录请求 - 开启协程
        try {

            //  协程作用域
            lifecycleScope.launch(Dispatchers.Main) {
                // 3.1 定义登录请求体
                val loginRequest = LoginRequest(username, password)
                // 3.2 转换至IO线程 - 发送登录请求
                val res = withContext(Dispatchers.IO) {
                    RetrofitClient.apiService.login(loginRequest)
                }
                // 3.3 根据返回结果判断
                if (res.code == 10000) {

                    // --------------- 获得token ---------------
                    val token = res.data?.token
                    // 判断token是否为空
                    if (token.isNullOrEmpty()) {
                        Toast.makeText(this@LoginActivity, "登录失败", Toast.LENGTH_SHORT).show()
                        return@launch
                    }
                    // 持久化存储 token
                    TokenPreferences.getInstance(this@LoginActivity).saveToken(token)
                    // ------------------------------
                    Toast.makeText(this@LoginActivity, "登录成功 ", Toast.LENGTH_SHORT).show()
                    // 3.4 跳转到主页
                    startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                    finish()
                } else {
                    Toast.makeText(this@LoginActivity, "登录失败", Toast.LENGTH_SHORT).show()
                }
            }

        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show()
        }
    }

    fun checkRequiredPermissions() {
        val locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
        val isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        if (!isGpsEnabled) {
            startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
        } else {

            if (hasInitAMap == false) {
                AmapUtils.updatePrivacyCompliance(this)
                hasInitAMap = true
            }

            if (EasyPermissions.hasPermissions(this, *mPermissions)) {
                if (hasInitAMap == false) {
                    AmapUtils.updatePrivacyCompliance(this)
                    hasInitAMap = true
                }
            } else {
                EasyPermissions.requestPermissions(
                    this,
                    "需要位置权限以提供准确的天气信息",
                    RC_LOCATION_PERM,
                    *mPermissions
                )
            }
        }
    }
}